#include "client.h"

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int socketFd;
    //初始化一个socket，有一个缓冲区
    socketFd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");
    printf("client : socketFd=%d\n",socketFd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_port=htons(atoi(argv[2]));
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    int ret;
    ret=connect(socketFd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    printf("client : connected\n");

    char buf[1000] = {0};
    //接收文件名
    int dataLen = 0;
    recv(socketFd,&dataLen,sizeof(int),MSG_WAITALL);//length of filename
    recv(socketFd,buf,dataLen,MSG_WAITALL);//filename

    //接收 文件大小
    off_t fileLen = 0;
    recv(socketFd,&dataLen,sizeof(int),MSG_WAITALL);
    recv(socketFd,&fileLen,dataLen,MSG_WAITALL);
    //printf("recv fileLen: %ld\n",fileLen);
    //创建新文件准备接收
    int fd;
    int i = 1;
    int buflen = strlen(buf);
    int tmp = buflen;
    // 这里实现如果有重名的文件，则在新建文件名后边加递增的数字，直到没有重名
    while(-1 == (fd = open(buf,O_RDWR|O_CREAT|O_EXCL,0666)))
    {
        tmp = buflen;
        while(buf[tmp])
        {
            buf[tmp++] = 0;
        }
        sprintf(buf,"%s%d",buf,i++);
    }


    //接收文件内容
    printf("Receiving file : name %s size : %ld M\n",buf,fileLen/(1024*1024));
    //增加客户端计时
    struct timeval st,end;
    gettimeofday(&st,NULL);
    //借助mmap，利用DMA 加快文件下载速度
    //
    //mmap前，先ftruncate改变文件大小
    ftruncate(fd,fileLen);
    char *pmap = (char *)mmap(NULL,fileLen,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    ERROR_CHECK(pmap,(char*)-1,"mmap");
    ret = recvCycle(socketFd,pmap,fileLen);
    
    if(!ret)
    {
        munmap(pmap,fileLen);
        gettimeofday(&end,NULL);
        printf("download success ,time use: %.2lf s\n",\
               (double)((end.tv_sec-st.tv_sec)*1000000+end.tv_usec-st.tv_usec)/1000000);
    }
    else
    {
        printf("Load failed!\n");
    }

    close(socketFd);
    return 0;
}
